/**
 * Copyright(C)版权所有 中国电子科技集团公司第三十二研究所
 *
 * @Title: 文件导入控制器文件
 * @author: 徐文远、肖小霞
 * @version: 1.0
 * @date: 2020/10/16
 * 备注:无
 */
package com.cetc32.dh.controller.rest;

import com.cetc32.dh.common.response.PageDataResult;
import com.cetc32.dh.common.response.ResponseResult;
import com.cetc32.dh.entity.DataFile;
import com.cetc32.dh.entity.DataSubmit;
import com.cetc32.dh.entity.FileToMenu;
import com.cetc32.dh.service.DataFileService;
import com.cetc32.dh.service.DataMenuService;
import com.cetc32.dh.service.DataSubmitService;
import com.cetc32.dh.service.FileToMenuService;
import com.cetc32.dh.utils.FileUtil;
import com.cetc32.dh.service.AdminUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Component
@RestController
@RequestMapping("/rest/import/")
public class FileSubmitController {

    @Autowired
    DataSubmitService dataSubmitService;
    @Autowired
    DataFileService dataFileService;
    @Autowired
    FileToMenuService fileToMenuService;
    @Autowired
    DataMenuService dataMenuService;
    @Autowired
    AdminUserService adminUserService;


    @Value("${upLoadPath}")
    String upLoadPath;

//    /**
//     * 批量文件夹上传服务器
//     * @param folder  批量文件
//     * @param dataSubmit  数据信息
//     * @return ResponseResult   网页返回结果
//     * **/
//    @ApiOperation(value="批量文件上传")
//    @PostMapping("/uploadFolder")
//    public ResponseResult  uploadFolder(MultipartFile[] folder,DataSubmit dataSubmit) {
//        dataSubmit=new DataSubmit(1,2,2,2,"SDF","DSF",3,"FG","DDD","DF",2011);
//        System.out.println(uploadPath);
//        System.out.println(folder.length);
//        FileUtil.saveMultiFile(uploadPath, folder);
//        dataSubmit.setSubtype(1);
//        dataSubmit.setStatus(1);
//        int count = dataSubmitService.insertDataSubmit(dataSubmit);
//        if(0<=count){
//            return ResponseResult.success("数据提交成功！");
//        }
//        return ResponseResult.error("数据提交失败！");
//    }

    /**
     * 查询当前用户提交的所有导入请求
     * @return 返回给前端分装好的结构体
     * **/
    @ApiOperation(value = "当前用户名提交的数据")
    @PostMapping("/request")
    public PageDataResult mySubmits(Integer page, Integer results) {
        DataSubmit ds = new DataSubmit();
        ds.setSubmitor("admin");
        List<DataSubmit> list = new ArrayList<>();
        Integer count = 0;
        list = dataSubmitService.selectMySubmit(ds);
        count = dataSubmitService.countMineSubmit(ds);
        return new PageDataResult(count, list, (page - 1) * results);

    }

    /**
     * 查询当前用户可以审核的所有导入请求
     * @return 返回给前端分装好的结构体
     * **/
    @ApiOperation(value = "当前用户名下需要审核及已审核的所有任务")
    @PostMapping("/task")
    public PageDataResult myApproves(Integer page, Integer results) {
        DataSubmit ds = new DataSubmit();
        ds.setSubmitor("admin");
        List<DataSubmit> list = new ArrayList<>();
        Integer count = 0;
        list = dataSubmitService.selectMyApprove(ds);
        for (int i = 0; i < list.size(); i++) {
        }
        count = dataSubmitService.countMineApprov(ds);
        return new PageDataResult(count, list, (page - 1) * results);
//        return new PageDataResult(count,list);
    }

    /**
     * 拒绝导入请求
     * @param map
     * @return 返回执行结果
     * **/
    @ApiOperation(value = "拒绝请求")
    @PostMapping("/reject")
    @ApiImplicitParam(name = "ids", value = "申请审批的记录id", dataType = "List", defaultValue = "")
    public ResponseResult rejectSubmit(@RequestBody Map<String, Object> map) {
        List<Integer> ids = new ArrayList<>();
        ids = (List<Integer>) map.get("ids");
        DataSubmit dataSubmit = null;
        int sum = 0;
        for (int i = 0; i < ids.size(); i++) {
            Integer id = ids.get(i);
            dataSubmit = dataSubmitService.queryById(id);
            if (dataSubmitService.rejectSubmit(dataSubmit) > 0) {
                String delFile = dataSubmit.getPath() + File.separator + dataSubmit.getTitle();
                System.out.println(delFile);
                FileUtil.deleteDir(delFile);
                sum = sum + 1;
            }
        }
        if (sum == ids.size())
            return ResponseResult.success("已审批拒绝");
        return ResponseResult.error("审批失败");
    }

    /**
     * 拒绝导入请求
     * @return 返回执行结果
     * **/
    @ApiOperation(value = "审核通过")
    @PostMapping("/accept")
    @ApiImplicitParam(name = "ids", value = "申请审批的记录id", dataType = "List", defaultValue = "")
    public ResponseResult acceptSubmit(@RequestBody Map<String, Object> map) {
        System.out.println(map);
        List<Integer> ids = new ArrayList<>();
        ids = (List<Integer>) map.get("ids");
        DataSubmit dataSubmit = null;
        DataFile dataFile = new DataFile();
        DataFile new_dataFile = null;
        FileToMenu fileToMenu = new FileToMenu();
        int sum = 0;
        for (int i = 0; i < ids.size(); i++) {
            Integer id = ids.get(i);
            dataSubmit = dataSubmitService.queryById(id);
            dataSubmit.setReviewTime(new Date());
            System.out.println(dataSubmit);
            dataFile.setFileName(dataSubmit.getTitle());
            dataFile.setFilePath(dataSubmit.getPath());
            dataFile.setRegion(dataSubmit.getArea());
            dataFile.setFileYear(dataSubmit.getYear());
            dataFile.setFileDiscription(dataSubmit.getFileDiscription());
            dataFile.setFileNumbers(dataSubmit.getFileNumbers());
            dataFile.setFileSize(dataSubmit.getFileSize());
            dataFile.setFileSecurity(dataSubmit.getPlevel().toString());
            dataFile.setApprover(dataSubmit.getApprover());
            dataFile.setSubmitor(dataSubmit.getSubmitor());
            dataFile.setFileType(dataSubmit.getTitle().substring(dataSubmit.getTitle().lastIndexOf(".") + 1));
            if (i != 0) {
                dataFile.setId(dataFile.getId() + i);
            }
            int flag_file = dataFileService.insertDataFile(dataFile);
            new_dataFile = dataFile;
            System.out.println(new_dataFile);
            fileToMenu.setFileId(new_dataFile.getId());
            fileToMenu.setMenuId(dataSubmit.getMenuid());
            int flag_filetomenu = fileToMenuService.insert(fileToMenu);
            if (flag_file > 0 && flag_filetomenu > 0) {
                if (dataSubmitService.acceptSubmit(dataSubmit) > 0) {
                    sum = sum + 1;
                }
            }
        }
        if (sum == ids.size())
            return ResponseResult.success("已审批通过");
        return ResponseResult.error("审批失败");
    }

    /**
     * @param page 页码
     * @param results 每页显示条数
     * @return 分页数据
     * */
    @ApiOperation(value = "所有待审核的数据")
    @PostMapping("/approves")
    public PageDataResult myAprroves(@ApiParam(value = "页码") Integer page, @ApiParam(value = "每页数据条数") Integer results) {
        if (null == page || page <= 0)
            page = 1;
        if (null == results || results <= 0)
            results = 10;
        DataSubmit ds = new DataSubmit();
        ds.setStatus(0);
        List<DataSubmit> list = new ArrayList<>();
        list = dataSubmitService.selectReadyApprove(ds);
        List<DataSubmit> list_new = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String menuName = dataMenuService.queryById(list.get(i).getMenuid()).getMenuName();
            list.get(i).setMenuName(menuName);
        }
        return new PageDataResult(dataSubmitService.countReadyApprove(ds),
                list, (page - 1) * results);
    }


    /**
     * 提交数据
     //     * @param dataSubmit 数据信息
     * @return 返回提交结果
     * */
    @ApiOperation(value = "提交数据", notes = "id不传参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "记录id号(不传参)", paramType = "body", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "subtype", value = "提交类型", paramType = "body", dataType = "String", defaultValue = ""),
            @ApiImplicitParam(name = "plevel", value = "文件等级", paramType = "body", dataType = "Integer", defaultValue = ""),
            @ApiImplicitParam(name = "status", value = "文件状态", paramType = "body", dataType = "Integer", defaultValue = ""),
            @ApiImplicitParam(name = "submitor", value = "提交者", paramType = "body", dataType = "String", defaultValue = ""),
            @ApiImplicitParam(name = "approver", value = "审核人", paramType = "body", dataType = "String", defaultValue = ""),
            @ApiImplicitParam(name = "menuid", value = "编目号", paramType = "body", dataType = "Integer", defaultValue = ""),
            @ApiImplicitParam(name = "menuName", value = "编目名称", paramType = "body", dataType = "String", defaultValue = ""),
            @ApiImplicitParam(name = "year", value = "年份", paramType = "body", dataType = "Integer", defaultValue = ""),
            @ApiImplicitParam(name = "title", value = "标题", paramType = "body", dataType = "String", defaultValue = ""),
            @ApiImplicitParam(name = "area", value = "区域", paramType = "body", dataType = "String", defaultValue = ""),
            @ApiImplicitParam(name = "path", value = "提交路径(不传参)", paramType = "body", dataType = "String", defaultValue = ""),
            @ApiImplicitParam(name = "userId", value = "用户id", paramType = "body", dataType = "Integer"),
    })
    @PostMapping("/sub")
    public ResponseResult DataSub(@RequestBody DataSubmit dataSubmit) {
        String userId=dataSubmit.getUserId();
        userId="1";
        String upCachePath=upLoadPath+"_user"+userId;
        System.out.println(dataSubmit);
        String fileName = null;
        Integer count = 0;
        dataSubmit.setSubtype("1");
        dataSubmit.setStatus(0);
        dataSubmit.setApprover("审核人");
        if((adminUserService.getUserById(Integer.parseInt(userId)))!=null){
            dataSubmit.setSubmitor(adminUserService.getUserById(Integer.parseInt(userId)).getSysUserName());
        }
        DataSubmit dataSubmit_new = dataSubmit;
        DataSubmit dataSubmit_new2 = dataSubmit;
        String path = dataMenuService.queryById(dataSubmit.getMenuid()).getUrl();
        dataSubmit.setPath(path);
        File baseFile = new File(upCachePath);
        File[] files = baseFile.listFiles();
        File file = null;
//        List<String> pathListNew = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            file = files[i];
            if (file.isDirectory()) {
                dataSubmit.setFileNumbers(FileUtil.getAllFile(upCachePath +File.separator+ file.getName()).size());
                dataSubmit.setFileSize(FileUtil.FormetFileSize(FileUtils.sizeOfDirectory(file)));
                fileName = FileUtil.getFileName(file.getName());
                file.renameTo(new File(upCachePath +File.separator+ fileName));
            } else {
                fileName = file.getName();
                dataSubmit.setFileSize(FileUtil.FormetFileSize(file.length()));
                dataSubmit.setFileNumbers(1);
            }
            dataSubmit.setTitle(fileName);
            dataSubmit.setSubtime(new Date());
            dataSubmit_new = dataSubmit;
            if (dataSubmitService.insertDataSubmit(dataSubmit_new) >= 0) {
                count++;
            }
            dataSubmit_new2 = dataSubmit_new;
            dataSubmit_new2.setId(dataSubmit_new.getId() + i + 1);
            dataSubmit_new.setId(dataSubmit_new2.getId());
        }

        if (FileUtil.copyFolder(upCachePath, path) && count == files.length) {
            FileUtil.deleteDir(upCachePath);
            return ResponseResult.success("表单信息提交成功！");
        }

        return ResponseResult.error("表单信息提交失败！");
    }


    /**
     * 目录/文件上传
     * @param file 目录，文件
     * @return 返回提交结果
     * */
    @ApiOperation(value = "文件上传")
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件夹下的文件list", paramType = "body", dataType = "List", defaultValue = ""),
            @ApiImplicitParam(name = "userId", value = "用户id", paramType = "body", dataType = "Integer"),
    })
    public ResponseResult uploadFile(@ApiParam(value = "二进制文件流")  MultipartFile[] file,String userId) {
//        String filepath = "/root/upLoad";
        userId="1";
        String upCachePath=upLoadPath+"_user"+userId;
        String filepath = upCachePath;
        String result = FileUtil.uploadFile(file, filepath);
        if (!result.contains("上传失败"))
            return ResponseResult.success(result);
        return ResponseResult.error(result);

    }


    /**
     * 文件上传缓冲区清空
     * @return 返回文件清空结果
     * */
    @ApiOperation(value = "清空历史上传")
    @RequestMapping(value = "/clearUploadFile", method = RequestMethod.POST)
    @ApiImplicitParam(name = "userId", value = "当前用户id")
    public ResponseResult clearUploadFile(String userId) {
        String upCachePath=upLoadPath+"_user"+userId;
        FileUtil.deleteDir(upCachePath);
        File file = new File(upCachePath);
        if (!file.exists()) {
            return ResponseResult.success("历史上传清空成功");
        }
        return ResponseResult.error("历史上传清空失败");
    }

    /**
     * 显示文件夹中文件详情
     * @return 返回文件夹中文件结果
     * */
    @ApiOperation(value = "显示文件夹中的文件")
    @PostMapping("/showFiles")
    @ApiImplicitParam(name = "fileId", value = "文件id号", paramType = "body", dataType = "String")
    public ResponseResult showFiles(@RequestBody String fileId) {
        System.out.println(fileId);
        if(dataFileService.queryById(Long.parseLong(fileId))!=null){
            String filePath = dataFileService.queryById(Long.parseLong(fileId)).getFilePath();
            String fileName = dataFileService.queryById(Long.parseLong(fileId)).getFileName();
            String whole_dir = filePath+File.separator+fileName;
            List<String> stringList = FileUtil.getAllFile(whole_dir);
            List<String> fileNames = new ArrayList<String>();
            for(int i=0;i<stringList.size();i++){
                fileNames.add(stringList.get(i).substring(stringList.get(i).indexOf(fileName)));
            }
            return ResponseResult.success(fileNames);
        }
        return ResponseResult.error("没有该文件夹！");
    }


}
